"""
标题行之后随机插入一段文字及一幅图片
"""
import pythoncom
import os
from docx import Document
from docx.opc.exceptions import PackageNotFoundError
from docx.shared import Inches


# 从最后开始替换某字符串几次
def rreplace(s, old, new, occurrence):
    li = s.rsplit(old, occurrence)
    return new.join(li)


# 读取文件夹下的特定格式文件名列表
def file_name(file_dir, file_format):
    fileList = []
    for root, dirs, files in os.walk(file_dir):
        for file in files:
            if os.path.splitext(file)[1] == file_format:
                fileList.append(os.path.join(root, file))
    return fileList


# 标题行之后插入一段文字及一幅图片
def add_para_picture(doc, para):
    run = doc.paragraphs[0].add_run(para)
    run.add_break()


# 随机取列表中的一个值返回
def pick_random_one(list):
    import random
    return random.choice(list)


# docx文件另存为doc
def docx_to_doc(docxName):
    pythoncom.CoInitialize()
    try:
        doc = Document(docxName)
        docxName = rreplace(docxName, "\\docx\\", "\\", 1)
        doc.save(docxName.replace(".docx", ".doc"))
    except PackageNotFoundError:
        pass
    finally:
        # 释放资源
        pythoncom.CoUninitialize()


def main():
    fileList = file_name("C:\\Users\\Administrator\\Desktop\\2020.8.7-88篇棋牌\\N",".docx")
    print(len(fileList))
    paraList = ['扑克_具体玩法介绍', '扑克_安卓版下载', '扑克_手机版下载']
    for file in fileList:
        pythoncom.CoInitialize()
        doc = Document(file)
        para = pick_random_one(paraList)


if __name__ == '__main__':
    main()
